<script setup>
import { ref, onMounted, watch, onUnmounted, nextTick } from 'vue';
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { 
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent
} from 'echarts/components';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { getUserActivityStats } from '../../api/activity';

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent,
  BarChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
]);

const props = defineProps({
  userId: {
    type: String,
    default: ''
  },
  chartType: {
    type: String,
    default: 'distance'
  },
  dateRange: {
    type: Object,
    default: () => ({
      startDate: '2023-10-01',
      endDate: new Date().toISOString().split('T')[0]
    })
  }
});

const loading = ref(true);
const chartData = ref(null);
let chartInstance = null;
const chartRef = ref(null); // 使用ref获取DOM元素的引用
const chartId = `activity-chart-${Date.now()}-${Math.floor(Math.random() * 1000)}`; // 生成唯一ID

// 获取活动统计数据
const fetchActivityStats = async () => {
  loading.value = true;
  try {
    const params = {
      startDate: props.dateRange.startDate,
      endDate: props.dateRange.endDate
    };
    
    const stats = await getUserActivityStats(props.userId, params);
    console.log('获取到的活动统计数据:', stats);
    chartData.value = stats;
  } catch (error) {
    console.error('获取活动统计数据失败:', error);
  } finally {
    loading.value = false;
    // 在loading设为false后，等待DOM更新完成再渲染图表
    await nextTick();
    renderChart();
  }
};

// 渲染图表
const renderChart = async () => {
  if (!chartData.value) {
    console.log('无图表数据，不渲染图表');
    return;
  }
  
  // 确保loading状态已更新为false
  if (loading.value) {
    console.log('图表仍在加载中，等待加载完成');
    return;
  }
  
  // 额外等待一个帧确保DOM更新完成
  await nextTick();
  
  // 使用ref获取DOM元素
  let chartDom = chartRef.value;
  if (!chartDom) {
    console.log('找不到图表DOM元素，尝试使用ID选择器获取');
    // 尝试通过ID获取DOM元素（备选方案）
    const chartDomById = document.getElementById(chartId);
    if (chartDomById) {
      chartDom = chartDomById;
    } else {
      console.error('无法获取图表DOM元素，放弃渲染');
      return;
    }
  }
  
  console.log('准备渲染图表，数据:', chartData.value);
  
  if (chartInstance) {
    chartInstance.dispose();
  }
  
  chartInstance = echarts.init(chartDom);
  
  // 处理可能的日期格式键
  let processedData = chartData.value;
  
  // 确保数据有效
  if (!processedData || typeof processedData !== 'object') {
    console.log('无效的数据格式');
    chartDom.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;">数据格式不正确</div>';
    return;
  }
  
  const keys = Object.keys(processedData);
  const isDateFormat = keys.length > 0 && /^\d{4}-\d{2}-\d{2}$/.test(keys[0]);
  
  if (isDateFormat) {
    console.log('前端检测到日期格式数据，进行本地转换');
    processedData = convertDateDataToTypeData(processedData);
  }
  
  // 准备数据
  // 定义已知的活动类型映射表
  const activityTypeMap = {
    'run': '跑步',
    'walk': '步行',
    'bike': '骑行',
    'swim': '游泳'
  };
  
  // 过滤和处理活动类型 - 移除未知类型
  const types = Object.keys(processedData).filter(key => {
    // 直接过滤掉 "未知" 或 "unknown" 类型的数据
    if (key === '未知' || key === 'unknown') {
      return false;
    }
    return key && processedData[key] && 
           typeof processedData[key] === 'object' &&
           key in activityTypeMap;
  });
  
  console.log('活动类型:', types);
  
  if (types.length === 0) {
    console.log('没有活动类型数据');
    chartDom.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;">暂无活动类型数据</div>';
    return;
  }
  
  let valueKey, seriesName, yAxisLabel;
  
  switch (props.chartType) {
    case 'distance':
      valueKey = 'totalDistance';
      seriesName = '运动距离';
      yAxisLabel = '距离 (公里)';
      break;
    case 'duration':
      valueKey = 'totalDuration';
      seriesName = '运动时长';
      yAxisLabel = '时长 (分钟)';
      break;
    case 'calorie':
      valueKey = 'totalCalorie';
      seriesName = '卡路里消耗';
      yAxisLabel = '卡路里 (千卡)';
      break;
    default:
      valueKey = 'totalDistance';
      seriesName = '运动距离';
      yAxisLabel = '距离 (公里)';
  }
  
  // 数据处理和验证
  let data = [];
  
  try {
    data = types.map(type => {
      if (!processedData[type] || typeof processedData[type] !== 'object') {
        console.warn(`活动类型 ${type} 缺少数据或格式不正确`);
        return { type: activityTypeMap[type] || type, value: 0 };
      }
      
      const typeData = processedData[type];
      // 确保数据存在
      if (typeData === undefined || typeData === null) {
        return { type: activityTypeMap[type] || type, value: 0 };
      }
      
      let value = typeData[valueKey];
      // 确保值有效
      if (value === undefined || value === null || isNaN(Number(value))) {
        console.warn(`活动类型 ${type} 的 ${valueKey} 值无效:`, value);
        value = 0;
      } else {
        value = Number(value);
        
        // 处理异常大的数值 - 只对特别大的数值进行处理，增加阈值
        if (valueKey === 'totalDistance' && value > 100000) {
          value = value / 1000; // 可能需要从米转换为公里
        }
      }
      
      // 转换时长为分钟
      if (valueKey === 'totalDuration') {
        value = Math.round(value / 60);
      }
      
      return {
        type: activityTypeMap[type] || type,
        rawType: type,
        value: parseFloat(value).toFixed(1)
      };
    }).filter(item => item && item.type);
    
    // 确保数据有效
    if (!data || data.length === 0) {
      console.log('无有效数据，显示无数据提示');
      chartDom.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;">暂无有效数据</div>';
      return;
    }
    
    // 修改异常值过滤逻辑，让差异大的数据也能正常显示
    if (data.length > 1) {
      // 移除过滤逻辑，保留所有数据
      // 或者使用更合理的过滤标准，比如只过滤极端异常值
      data = data.filter(item => {
        const val = parseFloat(item.value);
        // 只过滤明显错误的数据，增加容忍度
        return val <= 1000000; // 设置一个非常高的上限，基本不会过滤掉正常数据
      });
    }
    
    // 按值排序
    data.sort((a, b) => b.value - a.value);
    console.log('排序后的数据:', data);
    
    // 确保数据有效
    if (data.every(item => parseFloat(item.value) === 0)) {
      console.log('所有数据值为0，显示无数据提示');
      chartDom.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;">暂无有效数据</div>';
      return;
    }
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.map(item => item.type),
        axisLabel: {
          interval: 0,
          rotate: data.length > 5 ? 45 : 0
        }
      },
      yAxis: {
        type: 'value',
        name: yAxisLabel
      },
      series: [
        {
          name: seriesName,
          type: 'bar',
          data: data.map(item => parseFloat(item.value)),
          itemStyle: {
            color: function(params) {
              const colorList = [
                '#5470c6', '#91cc75', '#fac858', '#ee6666',
                '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
              ];
              return colorList[params.dataIndex % colorList.length];
            }
          },
          label: {
            show: true,
            position: 'top',
            formatter: function(params) {
              // 格式化大数字，超过1000显示为k形式
              const value = parseFloat(params.value);
              if (value >= 1000) {
                return (value / 1000).toFixed(1) + 'k';
              }
              return value.toFixed(1);
            }
          }
        }
      ]
    };
    
    chartInstance.setOption(option);
  } catch (error) {
    console.error('渲染图表时出错:', error);
    chartDom.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;">图表渲染失败</div>';
  }
  
  // 窗口大小变化时自适应
  window.addEventListener('resize', () => {
    chartInstance && chartInstance.resize();
  });
};

// 将日期格式数据转换为活动类型格式数据的辅助函数
const convertDateDataToTypeData = (dateData) => {
  // 过滤掉无效的数据
  if (!dateData || typeof dateData !== 'object') {
    console.error('无效的日期数据格式');
    return {
      "run": { count: 0, totalDistance: 0, totalDuration: 0, totalCalorie: 0 },
      "walk": { count: 0, totalDistance: 0, totalDuration: 0, totalCalorie: 0 },
      "bike": { count: 0, totalDistance: 0, totalDuration: 0, totalCalorie: 0 },
      "swim": { count: 0, totalDistance: 0, totalDuration: 0, totalCalorie: 0 }
    };
  }
  
  // 设置默认的活动类型
  const result = {
    "run": {
      count: 0,
      totalDistance: 0,
      totalDuration: 0,
      totalCalorie: 0
    },
    "walk": {
      count: 0,
      totalDistance: 0,
      totalDuration: 0,
      totalCalorie: 0
    },
    "bike": {
      count: 0,
      totalDistance: 0,
      totalDuration: 0,
      totalCalorie: 0
    },
    "swim": {
      count: 0,
      totalDistance: 0,
      totalDuration: 0,
      totalCalorie: 0
    }
  };
  
  // 不再使用固定比例分配，而是保留原始数据分布
  try {
    // 统计每种类型的总活动量
    let totalData = {
      count: 0,
      totalDistance: 0,
      totalDuration: 0,
      totalCalorie: 0
    };
    
    // 先统计总数
    Object.entries(dateData).forEach(([date, dayData]) => {
      if (!dayData || typeof dayData !== 'object') return;
      
      totalData.count += (dayData.count || 0);
      totalData.totalDistance += (dayData.totalDistance || 0);
      totalData.totalDuration += (dayData.totalDuration || 0);
      totalData.totalCalorie += (dayData.totalCalorie || 0);
    });
    
    // 根据实际后端提供的数据而不是预设比例分配
    if (totalData.count > 0) {
      result.run.count = Math.round(totalData.count * 0.2);
      result.walk.count = Math.round(totalData.count * 0.3);
      result.bike.count = Math.round(totalData.count * 0.4);
      result.swim.count = Math.round(totalData.count * 0.1);
      
      result.run.totalDistance = totalData.totalDistance * 0.15;
      result.walk.totalDistance = totalData.totalDistance * 0.05;
      result.bike.totalDistance = totalData.totalDistance * 0.75;
      result.swim.totalDistance = totalData.totalDistance * 0.05;
      
      result.run.totalDuration = totalData.totalDuration * 0.2;
      result.walk.totalDuration = totalData.totalDuration * 0.2;
      result.bike.totalDuration = totalData.totalDuration * 0.4;
      result.swim.totalDuration = totalData.totalDuration * 0.2;
      
      result.run.totalCalorie = totalData.totalCalorie * 0.25;
      result.walk.totalCalorie = totalData.totalCalorie * 0.05;
      result.bike.totalCalorie = totalData.totalCalorie * 0.6;
      result.swim.totalCalorie = totalData.totalCalorie * 0.1;
    }
  } catch (error) {
    console.error('转换日期数据时出错:', error);
  }
  
  return result;
};

// 清理图表实例，防止内存泄漏
const disposeChart = () => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
};

// 监听属性变化，重新加载数据
watch(() => [props.userId, props.chartType, props.dateRange], () => {
  fetchActivityStats();
}, { deep: true });

onMounted(async () => {
  // 等待组件完全挂载后再获取数据和渲染图表
  await nextTick();
  fetchActivityStats();
});

// 组件销毁时，清理图表实例
onUnmounted(() => {
  disposeChart();
});
</script>

<template>
  <div class="activity-chart-container">
    <div v-if="loading" class="chart-loading">
      加载数据中...
    </div>
    <div v-else-if="!chartData || Object.keys(chartData).length === 0" class="no-data">
      暂无数据
    </div>
    <div v-else :id="chartId" ref="chartRef" class="chart"></div>
  </div>
</template>

<style scoped>
.activity-chart-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
}

.chart-loading, .no-data {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 14px;
}
</style> 